package com.example.demo.config;

import com.example.demo.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author shenb
 * @date 2022-06-28 14:31
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyCustomErrorController extends AbstractErrorController {

    private static final Logger logger = LoggerFactory.getLogger(MyCustomErrorController.class);

    private final ErrorAttributes errorAttributes;

    @Autowired
    public MyCustomErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
        this.errorAttributes = errorAttributes;
    }

    private ErrorAttributeOptions getErrorAttributeOptions(HttpServletRequest request, MediaType all) {
        return ErrorAttributeOptions.of(
                ErrorAttributeOptions.Include.MESSAGE,
                ErrorAttributeOptions.Include.EXCEPTION);
    }

    @RequestMapping
    public ResponseEntity<Result<Void>> error(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> attrs = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        String path = (String) attrs.get("path");
        switch (status) {
            case INTERNAL_SERVER_ERROR: {
                String exceptionClzName = (String) attrs.get("exception");
                Result<Void>result = Result.failure((String) attrs.getOrDefault("message", attrs.get("error")), null);
                return new ResponseEntity<>(result, status);
            }

            default: {
                logger.warn("Request[{}] failed with status[{}], msg: {}", path, status.value(), attrs.get("error"));
                Result<Void> result = Result.failure((String) attrs.get("error"), null);
                return new ResponseEntity<>(result, status);
            }
        }
    }

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    public ResponseEntity<String> mediaTypeNotAcceptable(HttpServletRequest request, Exception e) {
        logger.error("Global exception catch: mediaTypeNotAcceptable", e);

        HttpStatus status = getStatus(request);
        return ResponseEntity.status(status).build();
    }
}